package com.leyou.order.interceptors;

import com.leyou.common.auth.dto.Payload;
import com.leyou.common.auth.dto.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.holders.UserHolder;
import com.leyou.common.utils.CookieUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * @author 虎哥
 */
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取cookie中的token
        String token = CookieUtils.getCookieValue(request, "LY_TOKEN");
        try {
            // 解析用户信息
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, UserInfo.class);

            // 保存用户
            UserHolder.setUser(payload.getUserInfo());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("非法访问，用户未登录！");
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 移除用户
        UserHolder.remove();
    }
}
